<?php
/**
 * PushPlus推送功能
 */

require_once __DIR__ . '/functions.php';

/**
 * 发送PushPlus推送
 */
function sendPushPlus($token, $title, $content, $template = 'html') {
    if (empty($token)) {
        return ['success' => false, 'message' => 'PushPlus密钥不能为空'];
    }
    
    $data = [
        'token' => $token,
        'title' => $title,
        'content' => $content,
        'template' => $template
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, PUSHPLUS_API_URL);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($response === false) {
        return ['success' => false, 'message' => '请求失败'];
    }
    
    $result = json_decode($response, true);
    if (!$result) {
        return ['success' => false, 'message' => '响应解析失败'];
    }
    
    if ($result['code'] == 200) {
        return ['success' => true, 'message' => '推送发送成功'];
    } else {
        return ['success' => false, 'message' => $result['msg'] ?? '推送发送失败'];
    }
}

/**
 * 发送订单提交通知给管理员
 */
function notifyAdminOrderSubmitted($orderId, $userInfo, $orderInfo) {
    // 获取管理员信息
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM users WHERE is_admin = 1 AND status = 1");
    $stmt->execute();
    $admins = $stmt->fetchAll();
    
    foreach ($admins as $admin) {
        if ($admin['pushplus_enabled'] && !empty($admin['pushplus_token'])) {
            $title = '新订单提交提醒';
            $content = '<div style="font-family: Arial, sans-serif; padding: 20px;">
                <h2 style="color: #007bff; text-align: center;">🛒 新订单提交</h2>
                <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 15px 0;">
                    <h3 style="color: #495057; margin-bottom: 10px;">订单信息</h3>
                    <p><strong>订单ID：</strong>' . $orderId . '</p>
                    <p><strong>商品名称：</strong>' . htmlspecialchars($orderInfo['product_name']) . '</p>
                    <p><strong>平台订单号：</strong>' . htmlspecialchars($orderInfo['platform_order_no']) . '</p>
                    <p><strong>物流单号：</strong>' . htmlspecialchars($orderInfo['tracking_no']) . '</p>
                    <p><strong>下单金额：</strong>¥' . number_format($orderInfo['order_amount'], 2) . '</p>
                </div>
                <div style="background: #e7f3ff; padding: 15px; border-radius: 8px; margin: 15px 0;">
                    <h3 style="color: #0056b3; margin-bottom: 10px;">用户信息</h3>
                    <p><strong>用户名：</strong>' . htmlspecialchars($userInfo['username']) . '</p>
                    <p><strong>手机号：</strong>' . htmlspecialchars($userInfo['phone']) . '</p>
                    <p><strong>提交时间：</strong>' . date('Y-m-d H:i:s') . '</p>
                </div>
                <div style="text-align: center; margin-top: 20px;">
                    <a href="' . APP_URL . '/admin/orders.php" style="background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;">查看订单详情</a>
                </div>
            </div>';
            
            sendPushPlus($admin['pushplus_token'], $title, $content);
        }
    }
}

/**
 * 发送订单状态变更通知给用户
 */
function notifyUserOrderStatusChanged($userId, $orderId, $oldStatus, $newStatus, $settlementInfo = null) {
    $userInfo = getUserInfo($userId);
    
    if (!$userInfo || !$userInfo['pushplus_enabled'] || empty($userInfo['pushplus_token'])) {
        return;
    }
    
    $statusText = [
        'pending' => '未结算',
        'settled' => '已结算',
        'refunded' => '已退还'
    ];
    
    $statusColors = [
        'pending' => '#ffc107',
        'settled' => '#28a745',
        'refunded' => '#dc3545'
    ];
    
    $title = '订单状态更新提醒';
    $content = '<div style="font-family: Arial, sans-serif; padding: 20px;">
        <h2 style="color: #007bff; text-align: center;">📋 订单状态更新</h2>
        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 15px 0;">
            <h3 style="color: #495057; margin-bottom: 10px;">订单信息</h3>
            <p><strong>订单ID：</strong>' . $orderId . '</p>
        </div>
        <div style="background: #fff3cd; padding: 15px; border-radius: 8px; margin: 15px 0; text-align: center;">
            <h3 style="color: #856404; margin-bottom: 10px;">状态变更</h3>
            <p style="font-size: 18px;">
                <span style="background: ' . $statusColors[$oldStatus] . '; color: white; padding: 5px 10px; border-radius: 15px;">' . $statusText[$oldStatus] . '</span>
                <span style="margin: 0 10px;">→</span>
                <span style="background: ' . $statusColors[$newStatus] . '; color: white; padding: 5px 10px; border-radius: 15px;">' . $statusText[$newStatus] . '</span>
            </p>
        </div>';
    
    if ($newStatus == 'settled' && $settlementInfo) {
        $content .= '<div style="background: #d4edda; padding: 15px; border-radius: 8px; margin: 15px 0;">
            <h3 style="color: #155724; margin-bottom: 10px;">结算信息</h3>';
        
        if (isset($settlementInfo['amount'])) {
            $content .= '<p><strong>结算金额：</strong>¥' . number_format($settlementInfo['amount'], 2) . '</p>';
        }
        
        if (isset($settlementInfo['info'])) {
            $content .= '<p><strong>结算说明：</strong>' . htmlspecialchars($settlementInfo['info']) . '</p>';
        }
        
        $content .= '</div>';
    }
    
    $content .= '<div style="text-align: center; margin-top: 20px;">
        <a href="' . APP_URL . '/orders.php" style="background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;">查看我的订单</a>
    </div>
    <div style="text-align: center; margin-top: 10px; font-size: 12px; color: #6c757d;">
        更新时间：' . date('Y-m-d H:i:s') . '
    </div>
</div>';
    
    sendPushPlus($userInfo['pushplus_token'], $title, $content);
}

/**
 * 发送系统通知给用户
 */
function notifyUserSystemMessage($userId, $title, $message) {
    $userInfo = getUserInfo($userId);
    
    if (!$userInfo || !$userInfo['pushplus_enabled'] || empty($userInfo['pushplus_token'])) {
        return;
    }
    
    $content = '<div style="font-family: Arial, sans-serif; padding: 20px;">
        <h2 style="color: #007bff; text-align: center;">📢 系统通知</h2>
        <div style="background: #e7f3ff; padding: 15px; border-radius: 8px; margin: 15px 0;">
            <p style="font-size: 16px; line-height: 1.6;">' . nl2br(htmlspecialchars($message)) . '</p>
        </div>
        <div style="text-align: center; margin-top: 20px; font-size: 12px; color: #6c757d;">
            发送时间：' . date('Y-m-d H:i:s') . '
        </div>
    </div>';
    
    sendPushPlus($userInfo['pushplus_token'], $title, $content);
}